<?php
// +----------------------------------------------------------------------
// | my
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://isofttime.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: $this <498944516@qq.com>
// +----------------------------------------------------------------------
namespace app\we\model;

use think\Model;



class WeSceneQrcode extends Model
{

    protected $insert = ['status'=>1]; 
    // 根据scene_id,scene_str 获取二维码信息
    public function info($appid,$scene_id, $field = true)
    {
        
        if (!$scene_id) return false;
        $map['appid'] = $appid;
        if (is_numeric($scene_id)){
            $map['scene_id'] = $scene_id;
        }else{
            $map['scene_str'] = $scene_id;
        }
        
        return $this->field($field)->where($map)->find();
    }

    public function infoById($id, $field = true)
    {
        
        if (!$id) return false;
        $map['id'] = $id;
       
        return $this->field($field)->where($map)->find();
    }

     // 获取自增scene_id;
    public function autoScene_id($appid,$type=0)
    {
        if (!$appid) return false;
        $map['appid']=$appid;
        $map['qrcode_type']=$type;
        $max=$this->where($map)->max('scene_id');
        if ($type==0 and !$max) $max=320000;  //避免与永久二维码冲突
        if ($type==1 and !$max) $max=0;
        $scene_id=intval($max)+1;
       
        return $scene_id;
    }

    public function editData(){

      $data=input("post.");
    
      if ($data['id']){
         $res = $this->allowField(true)->where('id',$data['id'])->update($data);
      }else{
         $qrcode=get_qrcode($data['appid'],$data['qrcode_type']);
         if (!is_array($qrcode)) die($qrcode);
         $qrcode['aid']=session('aid');
         $res = $this->allowField(true)->data($data+$qrcode)->save();
         
      }
      
      return $res;
    }

   
     public function deskAdmin($data)
    {
       
        $admin=model('admin/AdminUser')->info($data['fans']['admin']);
        
        $map['shopid']=$admin['shopid'];
        $map['code']='DESK'.$data['before'];
        $map['qrcode_type']=1;
       
        $res=db('WeSceneQrcode')->where($map)->update(['admin'=>$admin['id']]);
        if ($res) return $data['before'].'号桌绑定成功，管理员'.$admin['name'];
        $qrocde=db('WeSceneQrcode')->where($map)->find();
        $admin=model('admin/AdminUser')->info($qrocde['admin']);
        return '绑定失败，'.$data['before'].'号桌当前管理员'.$admin['name'];
       
    }

    public function scanOrSubscribe($data)
    {

       
       switch ($data['back']) {
            case '关注':
              //查询这个顾客是谁推荐的
            
              $qrcode=model('we/WeSceneQrcode')->infoById($data['qrcode_id']);
           
              if ($qrcode['code']) $fans=model('we/WeFans')->info($qrcode['code']);
              if(!$data['fans']['subscribe_openid']){
                 $res=db('WeFans')->where('openid',$data['openid'])->update(['subscribe'=>1,'subscribe_openid'=>$fans['openid'],'subscribe_time'=>time()]);
                 $message=$fans['nickname'].'你推广的粉丝'.$data["nickname"].'关注了我们,消费后你将得到佣金！';
                 //这里应该是个模板消息
                 custom_message($fans['openid'],['msgtype'=>'text','text'=>['content'=>$message]]);
              if ($data['options']['tui_subscribe_card']){
                 $custom_message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$data['options']['tui_subscribe_card']]];
                 $error= custom_message($data['openid'],$custom_message);
              }

              }
             
              return '终于等到你，你扫码了好友'.$fans['nickname'].'的二维码关注我们';


              break;

            case '扫描':
              //查询这个顾客是谁推荐的
           
              
              $qrcode=model('we/WeSceneQrcode')->infoById($data['qrcode_id']);
            
              if ($qrcode['code']) $fans=model('we/WeFans')->info($qrcode['code']);

              custom_message($fans['openid'],['msgtype'=>'text','text'=>['content'=>$data['nickname'].'扫了你分享的二维码']]);
              if ($data['options']['tui_scan_card']){ 
                 $custom_message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$data['options']['tui_scan_card']]];
                 $error= custom_message($data['openid'],$custom_message);
              }
              return '你扫码了'.$fans['nickname'].'的微信二维码';


              break;

             case '积分':
             
                $qrcode=model('we/WeSceneQrcode')->infoById($data['qrcode_id']);
                if ($qrcode['code']) $fans=model('we/WeFans')->info($qrcode['code']);

                $res=model('we/WeFansCfo')->cfoScore($data['fans'],1,$data,$description='扫描'.$fans['nickname'].'积分',$message='');
               
                custom_message($fans['openid'],['msgtype'=>'text','text'=>['content'=>$data['nickname'].'扫了你的二维码获得了一个积分']]);
              break;

              case '推广':
                  return $this->tui($data);
              break;

             
        }


    }


    public function getQrcode0($data,$expire='604800',$down=0){
     
          $qrcode=get_qrcode($data['appid'],0,$expire);
          if (!isset($data['subscribe_answer']))$data['subscribe_answer']=$data['before'];
          if (!isset($data['SCAN_answer']))$data['SCAN_answer']=$data['before'];
          $qrcode['aid']=$data['aid'];
          $qrcode['title']=$data['fans']['nickname'];
          $qrcode['code']=$data['fans']['openid'];
          $qrcode['subscribe_answer']='Q'.$data['subscribe_answer'];
          $qrcode['SCAN_answer']='Q'.$data['SCAN_answer'];
          
          if ($down==1){

            $path="uploads/we/qrocde0";
            $qrcode_name=$qrcode['appid'].'_'.$qrcode['scene_id'].'.jpg';
            createFolder($path);
           
            get_file_from_net($qrcode['short_url'],$path,$qrcode_name);

            $qrcode_pic=$path."/".$qrcode_name;
            $qrcode['loc']=$qrcode_pic;
          }
          $res = model('we/WeSceneQrcode')->allowField(true)->data($qrcode)->save();
   
          return ($down==1?$qrcode['loc']:$qrcode['short_url']);

    }

    public function tui($data){
      
          $avatar=model('we/WeFans')->downAvatar($data['fans']);
          $data['subscribe_answer']='关注';
          $data['SCAN_answer']='扫描';
          $qrcode_pic=$this->getQrcode0($data,604800,1);
        
          $image = \think\Image::open($qrcode_pic);
          $image->thumb(180,180,\think\Image::THUMB_CENTER)->save($qrcode_pic);
        
          $image = \think\Image::open(get_cover($data['options']['tui_pic'], 'path'));
          $image->water($avatar,[150,200]);
          $image->water($qrcode_pic,[520,560]);
          $image->text('有效期至'.date('Y-m-d H:i',time()+604800),  'static/admin/fonts/HYQingKongTiJ.ttf', 24,'#ffffff',7,[170,-20]);
          $image->text("长按图片识别二维码\n领福利",  'static/admin/fonts/HYQingKongTiJ.ttf',30,'#551A8B',7,[150,-550]);
          $tui_pic="uploads/we/qrocde0/tui_".$data['fans']['openid'].'.jpg';
          $image->save($tui_pic);


          $pic=upload_media($data['appid'],$tui_pic);
          
          $reply['touser']=$data['fans']['openid'];
          $reply['msgtype']='image';
          $reply['image']=['media_id'=>$pic['media_id']];

          custom_message($data['openid'],$reply);
          return '分享图片给朋友，朋友扫扫得卡券，朋友消费有优惠，朋友消费你分红，本图片有效期至'.date('Y-m-d H:i',time()+604800).",逾期你可以再次生成你的推广图片！";
      

    }

    public function beforeWord($data){
      if ($data['before']=='积分'){
       return $this->getQrcode0($data,$data['back']);
      }
    }




    

   
   
}